﻿using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;

/*----------------------------------------------------------------
* 描述 ：
* 用于帮助反射项目中的Controller
* 作    者 ：Tengsheng Hou
* 更新时间 ：2019/7/23 13:37:29
//----------------------------------------------------------------*/
namespace Core.Toolkit.Core.Api
{
    public static class ControllerReflectHelp
    {
        public static List<Type> GetAllController()
        {
            List<Type> types = new List<Type>();
            var basePath = AppDomain.CurrentDomain.BaseDirectory;
            DirectoryInfo root = new DirectoryInfo(basePath);
            FileInfo[] files = root.GetFiles("*.dll", SearchOption.AllDirectories);
            foreach (var file in files)
            {
                Assembly assembly = Assembly.LoadFile(file.FullName);
                List<Type> ts = assembly.GetTypes().ToList();
                var classList = ts.Where(a => a.IsClass && a.IsSubclassOf(typeof(ControllerBase)));
                if (classList != null && classList.Any())
                    types.AddRange(classList);
            }
            return types;
        }


        public static Type GetControllerType(string controllerName)
        {
            var list = GetAllController();
            return list.Where(a => a.Name.Contains(controllerName, StringComparison.InvariantCultureIgnoreCase)).FirstOrDefault();
        }
    }
}
